package com.example.lin.fragment_manager.activity;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

import com.example.lin.fragment_manager.R;
import com.example.lin.fragment_manager.fragment.AFragment;
import com.example.lin.fragment_manager.fragment.BFragment;
import com.example.lin.fragment_manager.fragment.CFragment;
import com.example.lin.fragment_manager.fragment.DFragment;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        showFragment(0);
    }

    //碎片容器
    private Fragment[] fragments = new Fragment[4];

    private int currentIndex = -1;//当前显示哪一个碎片 3

    /**
     * 显示碎片
     *
     * @param nextIndex 下一个需要显示的位置
     */
    private void showFragment(int nextIndex) {//0
        if (nextIndex == currentIndex) {//如果手残一直点击同一个按钮,直接返回
            return;
        }
        //开启碎片事物
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
//        if (nextIndex>currentIndex){
            ft.setCustomAnimations(R.anim.right_in, R.anim.left_out);
//        }else{
//
//        }
        //该碎片是否添加过
        if (fragments[nextIndex] == null) {
            switch (nextIndex) {
                case 0:
                    fragments[nextIndex] = new AFragment();
                    break;
                case 1:
                    fragments[nextIndex] = new BFragment();
                    break;
                case 2:
                    fragments[nextIndex] = new CFragment();
                    break;
                case 3:
                    fragments[nextIndex] = new DFragment();
                    break;
            }
            //添加
            ft.add(R.id.fl_container, fragments[nextIndex]);
        } else {
            //该碎片已经添加过,直接显示即可
            ft.show(fragments[nextIndex]);
//            ft.attach(fragments[nextIndex]);
        }
        //是否不是第一次添加,如果不是,则隐藏当前碎片(因为要显示下一个了)
        if (currentIndex != -1) {
            ft.hide(fragments[currentIndex]);
//            ft.detach(fragments[currentIndex]);
        }
        //提交事务
        ft.commit();
        //时刻保存当前显示的页面的位置
        currentIndex = nextIndex;
    }

    /**
     * 事务:处理组合
     * show & hide:不走生命周期,但 onHiddenChange方法会被调用
     * attach & detach : attach(onCreateView->onStart->onResume),detach(onPause->onStop->onDestroyView)
     */


    public void btn1(View view) {
        showFragment(0);
    }

    public void btn2(View view) {
        showFragment(1);
    }

    public void btn3(View view) {
        showFragment(2);
    }

    public void btn4(View view) {
        showFragment(3);
    }


}
